package kr.saeildamil.androidStudy_second.fragment.network;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class DownImage extends Activity {
	Button downBtn;
	ImageView imageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);

		downBtn = new Button(this);
		downBtn.setText("Download Image");
		downBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				new DownThread(
						"http://postfiles15.naver.net/20120608_46/seshana_13391382664380MTYx_JPEG/ahmix_naver_com_20120513_113449_jpg.jpg?type=w2")
						.start();
			}
		});

		imageView = new ImageView(this);

		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		layout.addView(downBtn, params);
		layout.addView(imageView, params);

		setContentView(layout);
	}

	class DownThread extends Thread {
		String mAddr;

		public DownThread(String mAddr) {
			super();
			this.mAddr = mAddr;
		}

		public void run() {
			super.run();
			InputStream is = null;
			try {
				is = new URL(mAddr).openStream();
				Bitmap bit = BitmapFactory.decodeStream(is);
				is.close();
				Message message = mAfterDown.obtainMessage();
				message.obj = bit;
				mAfterDown.sendMessage(message);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	Handler mAfterDown = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bitmap bit = (Bitmap) msg.obj;
			if (bit == null) {
				Toast.makeText(DownImage.this, "bitmap is null",
						Toast.LENGTH_SHORT).show();
			} else {
				imageView.setImageBitmap(bit);
			}
		}
	};
}
